package com.bi.myvitamio2;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Display;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bi.myvitamio2.bean.ScreenBean;
import com.bi.myvitamio2.utils.LocUtil;
import com.opendanmaku.DanmakuItem;
import com.opendanmaku.DanmakuView;
import com.opendanmaku.IDanmakuItem;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

import io.vov.vitamio.LibsChecker;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.utils.Log;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;

//在原来的基础上 增加了横竖屏判断实现了   controller中增加了reset功能以及构造函数（指定出现位置）  隐藏了seekbar等控件   VideoView中更改surfaceHolder宽高
//竖屏显示其他布局   横屏隐藏其它布局解决 全屏时controller不在底部问题
//增加了全屏按钮（利用接口回调将事件从controller传到VideoView再传到PlayActivity）
//增加了加载时的图片 设置VideoView的背景为纯黑 播放时设为透明  避免一开始进入时的透明状态
public class PlayActivity extends Activity implements VideoView.ActionInterface {
    /** 当前视频路径 */
    private String path ="rtmp://live.hkstv.hk.lxdns.com/live/hks";
   // private String path ="rtmp://192.168.201.209:1935/live1/13718757521";
  //  private String path ="http://111.202.98.178/tc-tct.douyucdn.cn/dyliveflv3/308211rcMCgvk5cZ.flv?mkey=577e2c230273e89a&f=1496&c=0&wsAuth=efada250f2da0545bb389e72f8391246&token=web-0-308211-3be44eee8ada92b3b89ef577d54d6161&logo=0&expire=0&p=.flv";

    //private String path ="http://mvvideo1.meitudata.com/5704a8ffdf7b14102.mp4";
            //gESD--->/storage/emulated/0     gESPD--->/storage/emulated/0/Music
    /** 当前声音 */
    private int mVolume = -1;
    /** 最大音量 */
    private int mMaxVolume;
    /** 当前亮度 */
    private float mBrightness = -1f;
    /** 手势数目 */
    private int finNum=0;

    private View mVolumeBrightnessLayout;//提示窗口
    private ImageView mOperationBg;//提示图片
    private TextView mOperationTv;//提示文字
    private AudioManager mAudioManager;
    private VideoView mVideoView;
    private GestureDetector gestDetector;
    private ScaleGestureDetector scaleDetector;

    private ScreenBean screenBean;

    private Button btn;
    private View fl_Video,ll_Play;
    private TextView iv_fl_video;
    private PopupWindow popupWindow;
    private ListView listView_popup;
    private TextView tv_huazhi;//画质的TextVeiw

    private DanmakuView mDanmakuView;
    private boolean isDanmuShow=false;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        if (!LibsChecker.checkVitamioLibs(this))
            return;

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_play);


        init();
        Toast.makeText(PlayActivity.this, "create-------", Toast.LENGTH_SHORT).show();
    }

    @Override//************************
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            ImageButton imageButton= mVideoView.getFullButton();
            if(imageButton!=null) {
                imageButton.setImageResource(R.drawable.ic_fullscreen_pre);
            }
            int mOrientation = PlayActivity.this.getResources().getConfiguration().orientation;
            if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
                PlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                ll_Play.setVisibility(View.VISIBLE);
                //恢复到原来的情况
                mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void init() {
        ll_Play=findViewById(R.id.ll_Play);
        fl_Video=findViewById(R.id.fl_Video);
        iv_fl_video= (TextView) findViewById(R.id.iv_fl_Video);
        //初始化 弹幕
        mDanmakuView = (DanmakuView) findViewById(R.id.danmakuView);
        List<IDanmakuItem> list = initItems();
        // Collections.shuffle(list);
        mDanmakuView.addItem(list, true);

        //初始化  画质的popupwindow
        View layout = LayoutInflater.from(this).inflate(R.layout.popupview, null);
        listView_popup = (ListView) layout.findViewById(R.id.popup_listView);
        ArrayList<String>arrayList=new ArrayList<>();
        arrayList.add("流畅");
        arrayList.add("普清");
        arrayList.add("高清");

        ArrayAdapter adapter_huazhi=new ArrayAdapter<String>(this,R.layout.popupitem,R.id.tv_popupitem,arrayList);
        listView_popup.setAdapter(adapter_huazhi);

        popupWindow = new PopupWindow(layout,100, 200);
        popupWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件

        popupWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.chunbai));// 设置背景图片，不能在布局中设置，要通过代码来设置
        popupWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
      /*  popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //popupwindow消失的时候恢复成原来的透明度
            }
        });*/

        mVideoView = (VideoView) findViewById(R.id.surface_view);

        listView_popup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        tv_huazhi.setText("流畅");
                        mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_LOW);
                        break;
                    case 1:
                        tv_huazhi.setText("普清");
                        mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_MEDIUM);
                        break;
                    case 2:
                        tv_huazhi.setText("高清");
                        mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
                        break;
                }
                mVideoView.setVideoPath(path);
                Toast.makeText(PlayActivity.this, "reset", Toast.LENGTH_SHORT).show();
                iv_fl_video.setVisibility(View.VISIBLE);
            }
        });

        mVolumeBrightnessLayout = findViewById(R.id.operation_volume_brightness);
        mOperationBg = (ImageView) findViewById(R.id.operation_bg);
        mOperationTv = (TextView) findViewById(R.id.operation_tv);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        mVideoView.setActionListener(this);//**********************

        mMaxVolume = LocUtil.getMaxVolume(this);
        gestDetector = new GestureDetector(this, new MyGestureListener());
        scaleDetector = new ScaleGestureDetector(this,
                new MultiGestureListener());

        screenBean = LocUtil.getScreenPix(this);
        if (path == "") {
            return;
        } else {
            mVideoView.setVideoPath(path);
            MediaController mc=new MediaController(this,this,true,fl_Video);
            mc.setVideoName("视频名字");
            mVideoView.setMediaController(mc);
            mc.setVisibility(View.GONE);//此操作是为了解决打开视频的时候控制条不走动，需要点击下视频才走动的问题。这样默认情况下用户看不到进度条，当点击视频的时候就可以看到正在走动的进度条了
            mVideoView.requestFocus();

            //mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);

            mVideoView
                    .setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mediaPlayer.setPlaybackSpeed(1.0f);
                        }
                    });

            //默认是1024*1024
            mVideoView.setBufferSize(8);

        }
    }

    private List<IDanmakuItem> initItems() {
        List<IDanmakuItem> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            IDanmakuItem item = new DanmakuItem(this, i + " : plain text danmuku", mDanmakuView.getWidth());
            list.add(item);
        }

        String msg = " : text with image   ";
        for (int i = 0; i < 100; i++) {
            ImageSpan imageSpan = new ImageSpan(this, R.drawable.em);
            SpannableString spannableString = new SpannableString(i + msg);
            spannableString.setSpan(imageSpan, spannableString.length() - 2, spannableString.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            IDanmakuItem item = new DanmakuItem(this, spannableString, mDanmakuView.getWidth(), 0, 0, 0, 1.5f);
            list.add(item);
        }
        return list;
    }

    private  void fullScreen(ImageButton mFullButton) {
        int mOrientation=PlayActivity.this.getResources().getConfiguration().orientation;
        if(mOrientation== Configuration.ORIENTATION_PORTRAIT) {
            PlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

            ll_Play.setVisibility(View.GONE);

            mFullButton.setImageResource(R.drawable.ic_fullscreen_nor);
            //让视频全屏
            mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
        }else{
            PlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            ll_Play.setVisibility(View.VISIBLE);

            mFullButton.setImageResource(R.drawable.ic_fullscreen_pre);
            //恢复到原来的情况
            mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
        }
    }
    private void huazhi(TextView mTv_huazhi){
        tv_huazhi=mTv_huazhi;
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();// 关闭
        } else {
            int[] location = new int[2];
            fl_Video.getLocationOnScreen(location);
            popupWindow.showAtLocation(fl_Video, Gravity.NO_GRAVITY, fl_Video.getWidth()-popupWindow.getWidth()-50, fl_Video.getHeight()-popupWindow.getHeight());
        }
    }


    /** 定时隐藏 */
    private Handler mDismissHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mVolumeBrightnessLayout.setVisibility(View.GONE);
        }
    };

    @Override  //全部将事件消费掉
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        finNum=event.getPointerCount();

        if (1 == finNum) {
            gestDetector.onTouchEvent(event);
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    endGesture();
            }
        } else if (2 ==finNum) {
            //TODO 是否取消缩放
           // scaleDetector.onTouchEvent(event);
        }
        return true;
    }

    /** 手势结束 */
    private void endGesture() {
        mVolume = -1;
        mBrightness = -1f;

        // 隐藏
        mDismissHandler.removeMessages(0);
        mDismissHandler.sendEmptyMessageDelayed(0, 500);
    }

    /**
     * 视频缩放
     */
    public void changeLayout(int size) {
        mVideoView.setVideoLayout(size, 0);
    }

    /**
     * 声音大小
     *
     * @param percent
     */
    public void changeVolume(float percent) {
        if (mVolume == -1) {
            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (mVolume < 0)
                mVolume = 0;
            // 显示
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
           // mOperationBg.setImageResource(R.drawable.video_volumn_bg);
            mOperationTv.setVisibility(View.VISIBLE);
        }
        int index = (int) (percent * mMaxVolume) + mVolume;
        if (index > mMaxVolume)
            index = mMaxVolume;
        else if (index < 0)
            index = 0;
        if (index >= 10) {
            mOperationBg.setImageResource(R.drawable.volmn_100);
        } else if (index >= 5 && index < 10) {
            mOperationBg.setImageResource(R.drawable.volmn_60);
        } else if (index > 0 && index < 5) {
            mOperationBg.setImageResource(R.drawable.volmn_30);
        } else {
            mOperationBg.setImageResource(R.drawable.volmn_no);
        }
        //DecimalFormat    df   = new DecimalFormat("######0.00");
        mOperationTv.setText((int) (((double) index / mMaxVolume) * 100) + "%");
        // 变更声音
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

    }

    /**
     * 亮度大小
     *
     * @param percent
     */
    public void changeBrightness(float percent) {
        if (mBrightness < 0) {
            mBrightness = getWindow().getAttributes().screenBrightness;
            if (mBrightness <= 0.00f)
                mBrightness = 0.50f;
            if (mBrightness < 0.01f)
                mBrightness = 0.01f;

            // 显示
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
           // mOperationBg.setImageResource(R.drawable.video_brightness_bg);
            mOperationTv.setVisibility(View.VISIBLE);

        }


        WindowManager.LayoutParams lpa = getWindow().getAttributes();
        lpa.screenBrightness = mBrightness + percent;
        if (lpa.screenBrightness > 1.0f)
            lpa.screenBrightness = 1.0f;
        else if (lpa.screenBrightness < 0.01f)
            lpa.screenBrightness = 0.01f;
        getWindow().setAttributes(lpa);

        mOperationTv.setText((int) (lpa.screenBrightness * 100) + "%");
        if (lpa.screenBrightness * 100 >= 90) {
            mOperationBg.setImageResource(R.drawable.light_100);
        } else if (lpa.screenBrightness * 100 >= 80 && lpa.screenBrightness * 100 < 90) {
            mOperationBg.setImageResource(R.drawable.light_90);
        } else if (lpa.screenBrightness * 100 >= 70 && lpa.screenBrightness * 100 < 80) {
            mOperationBg.setImageResource(R.drawable.light_80);
        } else if (lpa.screenBrightness * 100 >= 60 && lpa.screenBrightness * 100 < 70) {
            mOperationBg.setImageResource(R.drawable.light_70);
        } else if (lpa.screenBrightness * 100 >= 50 && lpa.screenBrightness * 100 < 60) {
            mOperationBg.setImageResource(R.drawable.light_60);
        } else if (lpa.screenBrightness * 100 >= 40 && lpa.screenBrightness * 100 < 50) {
            mOperationBg.setImageResource(R.drawable.light_50);
        } else if (lpa.screenBrightness * 100 >= 30 && lpa.screenBrightness * 100 < 40) {
            mOperationBg.setImageResource(R.drawable.light_40);
        } else if (lpa.screenBrightness * 100 >= 20 && lpa.screenBrightness * 100 < 20) {
            mOperationBg.setImageResource(R.drawable.light_30);
        } else if (lpa.screenBrightness * 100 >= 10 && lpa.screenBrightness * 100 < 20) {
            mOperationBg.setImageResource(R.drawable.light_20);
        }
    }




    /**
     * 单点触屏
     *
     * @author jin
     *
     */
    private class MyGestureListener implements GestureDetector.OnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            // TODO Auto-generated method stub
            Log.d("Fling", velocityY);
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // TODO Auto-generated method stub

        }
        //滑动事件监听
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            if(2==finNum){
                return false;
            }
//此处的mOldX我定义为e2
            float mOldX = e2.getX(), mOldY = e1.getY();
            int y = (int) e2.getRawY();
            int x = (int) e2.getRawX();
            Display disp = getWindowManager().getDefaultDisplay();
            int windowWidth = disp.getWidth();
            int windowHeight = disp.getHeight();
            if (mOldX > windowWidth * 3.0 / 4.0) {// 右边滑动 屏幕 3/4
                changeVolume((mOldY - y) / windowHeight);
            } else if (mOldX < windowWidth * 1.0 / 4.0) {// 左边滑动 屏幕 1/4
                changeBrightness((mOldY - y) / windowHeight);
            }

            // 隐藏
            mDismissHandler.removeMessages(0);
            mDismissHandler.sendEmptyMessageDelayed(0, 500);

            return false;
        }
        @Override
        public void onShowPress(MotionEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // TODO Auto-generated method stub
            return false;
        }
    }

    /**
     * 多点缩放
     *
     * @author jin
     *
     */
    private class MultiGestureListener implements ScaleGestureDetector.OnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            // 返回true ，才能进入onscale()函数
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            float oldDis = detector.getPreviousSpan();
            float curDis = detector.getCurrentSpan();
            if (oldDis - curDis > 50) {
                // 缩小
                changeLayout(0);
                Toast.makeText(PlayActivity.this, "缩小", Toast.LENGTH_SHORT).show();
            } else if (oldDis - curDis < -50) {
                // 放大
                changeLayout(1);
                Toast.makeText(PlayActivity.this, "放大", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    public void fullAction(ImageButton mFullButton) {
        fullScreen(mFullButton);
    }

    @Override
    public void HuazhiAction(TextView mTv_huazhi) {
        huazhi(mTv_huazhi);
    }

    @Override
    public void danmu() {

        if(mDanmakuView!=null){
            if(isDanmuShow){
                mDanmakuView.hide();
                isDanmuShow=false;
            }else {
                mDanmakuView.show();
                isDanmuShow=true;
            }

        }
    }

    @Override
    public void startPlayAction() {
        mVideoView.setBackgroundResource(R.color.transparent);
        Toast.makeText(PlayActivity.this, "kaishi", Toast.LENGTH_SHORT).show();
        iv_fl_video.setVisibility(View.GONE);
    }

    @Override
    public void prepareAction() {
        Toast.makeText(PlayActivity.this, "prepare", Toast.LENGTH_SHORT).show();
        iv_fl_video.setVisibility(View.VISIBLE);
    }
    @Override
    public void resetAction() {
        Toast.makeText(PlayActivity.this, "reset", Toast.LENGTH_SHORT).show();
        iv_fl_video.setVisibility(View.VISIBLE);
    }

    @Override
    public void dealError() {
        // TODO 处理视频播放不了的问题
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDanmakuView.clear();
    }
}


